package cn.dapeng.ticket;

import cn.dapeng.util.SleepingUtil;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Ticket_Demo02 {

    private final AtomicInteger tickets = new AtomicInteger(10000);

    private final Set<Integer> cache = new CopyOnWriteArraySet<>();

    public void sale() {
        int num = tickets.decrementAndGet();
        if (tickets.get() < 0) {
            System.exit(0);
        } else {
            SleepingUtil.sleep(1, TimeUnit.MILLISECONDS);
            if (cache.contains(num)) {
                System.out.println("Oops");
                System.exit(0);
            } else {
                cache.add(num);
            }
            System.out.println(Thread.currentThread().getName() + ":" + num);
        }
    }


    public static void main(String[] args) {
        Ticket_Demo02 demo02 = new Ticket_Demo02();

        new Thread(() -> {
            while (true) {
                demo02.sale();

            }

        }, "T1").start();

        new Thread(() -> {
            while (true) {
                demo02.sale();
            }
        }, "T2").start();
    }
}
